package com.demo.commons.config.filter;

import com.demo.commons.enums.Result;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class AuthorizationFilter extends OncePerRequestFilter {
    private static final String[] passedPaths = new String[]{"/login","/h2-console"};
    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        logger.info("AuthorizationFilter: started");
        String requestPath = request.getServletPath();
        if (antMatchers(requestPath)) {
            filterChain.doFilter(request, response);
        } else {
            String authorization = request.getHeader("authorization");

            if (Strings.isEmpty(authorization) || Strings.isBlank(authorization)) {
                logger.error("authorization failed : no authorization header");
                throw new IOException(Result.failed().getMessage());
            } else {
                logger.info("authorization is OK");
                filterChain.doFilter(request, response);
            }
        }
    }

    private boolean antMatchers(String requestPath) {
        boolean flag = false;

        for (String pattern : passedPaths) {

            if (antPathMatcher.match(pattern, requestPath)) {
                flag = true;
                break;
            }
        }

        return flag;
    }
}
